<template>
  <!-- #ifdef H5 -->
  <view class="custom-tab-bar">
    <view
      v-for="(item, index) in tabList"
      :key="index"
      class="tab-item"
      :class="{ active: current === index }"
      @click="switchTab(item, index)"
    >
      <image :src="current === index ? item.selectedIconPath : item.iconPath" class="tab-icon" />
      <text class="tab-text">{{ item.text }}</text>
    </view>
  </view>
  <!-- #endif -->
</template>

<script setup>
import { ref, watch } from 'vue'
import { onShow } from '@dcloudio/uni-app'
const current = ref(0)

const tabList = [
  {
    text: '设备',
    pagePath: '/pages/shebei/shebei',
    iconPath: 'static/tabs/device_default.png',
    selectedIconPath: 'static/tabs/device_selected.png',
  },
  {
    text: '查车',
    pagePath: '/pages/indexs/index',
    iconPath: '/static/tabs/car_default.png',
    selectedIconPath: '/static/tabs/car_selected.png',
  },
  {
    text: '报警',
    pagePath: '/pages/callPolice/callPolice',
    iconPath: '/static/tabs/police_default.png',
    selectedIconPath: '/static/tabs/police_selected.png',
  },
  {
    text: '我的',
    pagePath: '/pages/my/my',
    iconPath: '/static/tabs/user_default.png',
    selectedIconPath: '/static/tabs/user_selected.png',
  },
]

// const switchTab = (item, index) => {
//   current.value = index
//   // H5 端使用路由跳转（需要配置 vue-router）
//   // 如果是纯 UniApp 路由
//   uni.switchTab({
//     url: item.pagePath,
//   })
// }

// 关键修复 1：通过路由监听同步状态
const syncCurrentTab = () => {
  const pages = getCurrentPages()
  if (!pages.length) return

  const currentPage = pages[pages.length - 1]
  const currentPath = '/' + currentPage.route

  // 查找匹配的索引
  const index = tabList.findIndex(
    (item) => currentPath.startsWith(item.pagePath), // 模糊匹配兼容子页面
  )

  if (index !== -1) current.value = index
}

// 页面显示时同步状态
onShow(() => {
  syncCurrentTab()
})

// 关键修复 2：精确传递索引
const switchTab = (item, index) => {
  // 打印调试信息
  console.log('点击索引:', index, '对应路径:', item.pagePath)

  current.value = index // 立即更新状态
  uni.switchTab({
    // 确保跳转的是 tabBar 页面
    url: item.pagePath,
    success: () => console.log('跳转成功'),
    fail: (err) => console.error('跳转失败:', err),
  })
}
</script>

<style scoped>
.custom-tab-bar {
  position: fixed;
  bottom: -1px;
  left: 0;
  right: 0;
  height: 55px;
  background: #fff;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border-top: 1px solid #eee;
  /* 适配 iPhone 底部安全区域 */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

.tab-item {
  flex: 1;
  text-align: center;
}

.tab-icon {
  width: 24px;
  height: 24px;
  display: block;
  margin: 0px auto 4px;
}

.tab-text {
  font-size: 12px;
  color: #666;
}

.tab-item.active .tab-text {
  color: #4e6bb9;
}
</style>
